<template>
  <div class="examine-detail">
    <div class="examine-header">
      <span @click="close(true)">返回</span>
      <div>{{detailData.title}}</div>
      <div class="options">
        <el-popover
          popper-class="cus-popover"
          placement="bottom"
          :width="278"
          trigger="click"
          v-if="detailData.status === 1 || detailData.status === 0"
        >
          <template #reference>
            <div class="options-btn" ref="passBtn">通过</div>
          </template>
          <span class="examine-reason">审核意见：</span>
          <CurEditor
            :isDis="detailData.status ? true : false"
            v-model="passReason"
            :modelValue="passReason"
            height="130px"
            class="cus-editor"
            placeholder="请输入意见"
          />
          <div class="examine-pop-option" v-if="detailData.status === 0">
            <el-button size="mini" type="primary" @click="saveExamineStatus(1)">确定</el-button>
            <el-button size="mini" @click="hiddenPassPop">取消</el-button>
          </div>
        </el-popover>
        <el-popover
          popper-class="cus-popover"
          placement="bottom"
          :width="278"
          trigger="click"
          v-if="detailData.status === 2 || detailData.status === 0"
        >
          <template #reference>
            <div class="options-btn" ref="failBtn">不通过</div>
          </template>
          <span class="examine-reason">审核意见：</span>
          <CurEditor
            :isDis="detailData.status ? true : false"
            height="130px"
            v-model="failReason"
            :modelValue="failReason"
            placeholder="请输入意见"
            class="cus-editor"
          />
          <div class="examine-pop-option" v-if="detailData.status === 0">
            <el-button size="mini" type="primary" @click="saveExamineStatus(2)">确定</el-button>
            <el-button size="mini" @click="hiddenFailPop">取消</el-button>
          </div>
        </el-popover>
      </div>
    </div>
    <div class="examine-content">
      <div class="cus-tabs">
        <ul>
          <li
            v-for="item in classLsit"
            :key="item.value"
            :class="{ active: classType === item.value }"
            @click="classType = item.value"
          >{{ item.label }}</li>
        </ul>
      </div>
      <div class="deital-container">
        <div class="preview-container">
          <HandoutPreviewComponent
            v-if="handoutId && classType === 'handout' && previewType !== 1"
            class-preview
            :handout="handoutId"
          />
          <iframe
            v-else-if="handoutId && classType === 'handout' && previewType === 1"
            :src="`${basePath}${previewPath}`"
            frameborder="0"
            width="100%"
            height="100%"
          />
          <TestPaperPreview
            v-else-if="handoutId&&classType !== 'handout'"
            :previewNoRoute="true"
            :idNoRoute="handoutId"
          />
          <cus-empty v-else></cus-empty>
        </div>
        <div class="detail-info">
          <div class="prepare-info">
            <div class="prepare-title">
              <span>备课详情</span>
              <img src="/src/assets/one-examine/title-book.png" alt />
            </div>
            <div class="prepare-content">
              <div class="prepare-info-item">
                <span class="item-label">课次:</span>
                <span class="item-value">{{detailData.title}}</span>
              </div>
              <div class="prepare-info-item">
                <span class="item-label">教师:</span>
                <span class="item-value">{{detailData.creatorName}}</span>
              </div>
              <div class="prepare-info-item">
                <span class="item-label">{{examineInfo.type === 2 ? '小组课':'学生'}}:</span>
                <span class="item-value">{{detailData.lessonName}}</span>
                <span class="item-value" v-if="examineInfo.type === 2">({{studentList}})</span>
              </div>
              <div class="prepare-info-item">
                <span class="item-label">上课时间:</span>
                <span class="item-value">{{filterTime(detailData.classTime)}}</span>
              </div>
              <div class="teach-plan">
                <div class="teach-plan-header">
                  <div>
                    <img src="/src/assets/one-examine/teach-plan-header.png" alt />
                    <span>教学计划</span>
                  </div>
                  <span
                    class="plan-status-fail"
                    v-if="planStatus === 2 && teachPlanInfo"
                    @click="examineTeachPlan"
                  >审核未通过 >></span>
                  <span
                    class="plan-status-pass"
                    v-if="planStatus === 1 && teachPlanInfo"
                    @click="examineTeachPlan"
                  >审核通过 >></span>
                  <span
                    class="plan-status-normal"
                    v-if="planStatus === 0 && teachPlanInfo"
                    @click="examineTeachPlan"
                  >未审核 >></span>
                  <span class="plan-status-none" v-if="!teachPlanInfo">未添加 >></span>
                </div>
                <div v-if="teachPlanInfo" class="teach-plan-title">{{teachPlanInfo.indexName}}</div>
                <div class="teach-plan-info" v-if="teachPlanInfo">
                  <span class="plan-info-label">课次</span>
                  <span class="plan-info-value">{{teachPlanInfo.indexCount || 0}}</span>|
                  <span class="plan-info-label">总课时</span>
                  <span class="plan-info-value">{{teachPlanInfo.periodCount || 0}}课时</span>|
                  <span class="plan-info-label">已备课</span>
                  <span class="plan-info-value">{{teachPlanInfo.checked || 0}}次</span>
                </div>
              </div>
            </div>
          </div>
          <div class="prepare-info" v-if="handoutId && (previewType!==1)">
            <div class="prepare-title other-title">
              <span>
                {{
                classLsit.find((e) => e.value === classType).label
                }}详情
              </span>
            </div>
            <div class="prepare-content">
              <div class="prepare-info-item">
                <span class="item-label">名称:</span>
                <span class="item-value" v-if="classType === 'handout'">{{ handoutTitle }}</span>
                <span class="item-value" v-else>{{ testPaper.title }}</span>
              </div>
              <div class="prepare-info-item">
                <span class="item-label">题目数:</span>
                <span class="item-value">{{ filterHandoutCount()}}</span>
              </div>
              <div v-if="classType === 'handout'">
                <div class="prepare-info-item">
                  <span class="item-label">知识元:</span>
                  <span class="item-value">{{filterknowledgeNames()}}</span>
                </div>
                <div class="prepare-info-item">
                  <span class="item-label">保存时间:</span>
                  <span class="item-value">{{handoutSaveTime}}</span>
                </div>
              </div>
              <div v-else>
                <div class="prepare-info-item">
                  <span class="item-label">试题总分:</span>
                  <span class="item-value">{{questionScore}}</span>
                </div>
              </div>
              <div v-if="classType === 'homework'">
                <div class="prepare-info-item">
                  <span class="item-label">开始时间:</span>
                  <span class="item-value">{{homeworkSTime}}</span>
                </div>
                <div class="prepare-info-item">
                  <span class="item-label">结束时间:</span>
                  <span class="item-value">{{homeworkETime}}</span>
                </div>
              </div>
              <div class="important-pointer" v-if="classType === 'handout' && !teachPlanInfo">
                <div class="difficult"></div>
                <div style="text-align: center;">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="teachPlanInfo ? teachPlanInfo.difficultPoint :'暂无重难点描述'"
                    placement="top-start"
                  >
                    <el-button type="text">{{ teachPlanInfo  ? teachPlanInfo.difficultPoint : '暂无重难点描述' }}</el-button>
                  </el-tooltip>
                </div>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { inject, ref, watch, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import CurEditor from "./components/cur-editor.vue";
import HandoutPreviewComponent from "@/views/handout/index.vue";
import TestPaperPreview from "@/views/test-paper/update/index.vue";
import TeachPlan from "./teach-plan-info/index.vue";
import paperStore from "@/views/test-paper/update/store/index";
import axios from "axios";
import Moment from "moment";
import store from "../../handout/store/index";
import { screen, utils } from "$";
export default {
  components: { CurEditor, HandoutPreviewComponent, TestPaperPreview },
  props: {
    examineInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props) {
    onMounted(() => {
      axios
        .post("/admin/lessonAuditComment/queryComment", {
          auditId: props.examineInfo.id,
        })
        .then((res: any) => {
          passReason.value =
            props.examineInfo.status == 1 ? res.json.comment : "";
          failReason.value =
            props.examineInfo.status == 2 ? res.json.comment : "";
        });
    });
    let close: any = inject("close");
    let classLsit = [
      { label: "进门考", value: "test" },
      { label: "讲义", value: "handout" },
      { label: "作业", value: "homework" },
    ];
    let paperInfo: any = computed(() => store.state.paperInfo);
    let handoutTitle: any = computed(() => store.state.title);
    let handoutSaveTime: any = computed(() => store.state.saveTime);
    let testPaper: any = computed(() => paperStore.state.paperInfo);
    let questionCount: any = computed(() => {
      return testPaper.value.paperCharpts.reduce((q, e) => {
        return e.questionCount + q;
      }, 0);
    });
    let questionScore = computed(() => {
      return testPaper.value.paperCharpts.reduce((q, e) => {
        return e.totalScore + q;
      }, 0);
    });
    let classType = ref("handout");
    let passReason = ref("");
    let failReason = ref("");
    let handoutId = ref();
    let previewType = ref();
    let previewPath = ref();
    let detailData = ref(props.examineInfo);
    let testPaperPath = ref("");
    let passVisible = ref(false);
    let failVisible = ref(false);
    let studentList = ref("");
    let teachPlanInfo = ref({});
    let homeworkSTime = ref("");
    let homeworkETime = ref("");
    let planStatus = ref(0);
    let teachPlanId = ref("");
    let passBtn = ref();
    let failBtn = ref();
    let basePath = `${utils.generatBasePath()}furl=${
      import.meta.env.VITE_APP_BASE_URL
    }`;
    const urls = {
      test: "/admin/lessonEntranceExam/query",
      handout: "/admin/lessonAudit/queryDetails",
      homework: "/admin/lessonHomework/query",
    };
    const queryDetail = (url) => {
      const params =
        classType.value === "handout"
          ? {
              indexId: props.examineInfo.indexId,
            }
          : {
              lessonTimeId: props.examineInfo.indexId,
            };
      axios.post(url, params).then((res: any) => {
        if (res.result && res.json) {
          if (Object.prototype.toString.call(res.json) === "[object Array]") {
            res.json[0] && (handoutId.value = res.json[0].paperId);
            homeworkSTime.value = res.json[0].startTime
              ? Moment(res.json[0].startTime).format("YYYY-MM-DD HH:mm")
              : "";
            homeworkETime.value = res.json[0].endTime
              ? Moment(res.json[0].endTime).format("YYYY-MM-DD HH:mm")
              : "";
          } else {
            handoutId.value = res.json.handoutId;
            previewType.value = res.json.type;
            previewPath.value = res.json.path;
          }
        } else {
          ElMessage.error(res.msg);
        }
      });
    };
    queryDetail(urls[classType.value]);
    const filterTime = (val) => {
      return Moment(val).format(
        `YYYY-MM-DD ${new Date(val).getHours() > 12 ? "下午" : "上午"} HH:mm`
      );
    };
    const getStudentList = () => {
      axios
        .post(`/admin/lessonInfo/queryStudent`, {
          lessonId: props.examineInfo.lessonId,
          searchType: 2,
          id: props.examineInfo.lessonThirdId,
        })
        .then((res: any) => {
          studentList.value = res.json.map((ele) => ele.studentName).join(",");
        });
    };
    props.examineInfo.type === 2 && getStudentList();
    const getTeachPlanInfo = () => {
      let params = {
        lessonId: props.examineInfo.type === 1 ? props.examineInfo.contractId : props.examineInfo.lessonId,
        id: props.examineInfo.indexId,
      }
      axios
        .post(`/admin/lessonTimes/queryLessonAuditCalcu`, params)
        .then((res: any) => {
          if (!res.result) return ElMessage.error(res.msg);
          teachPlanInfo.value = res.json;
          res.json && (teachPlanId = res.json.planId);
        });
    };
    getTeachPlanInfo();
    const examineTeachPlan = async () => {
      /** 获取审核意见 */
      let res: any = await axios.post(
        `/admin/lessonTimesAuditComment/queryOneComment`,
        {
          lessonId: props.examineInfo.type === 1 ? props.examineInfo.contractId : props.examineInfo.lessonId,
          version: props.examineInfo.bindVersion,
        }
      );

      await screen.create(
        TeachPlan,
        {
          examineInfo: props.examineInfo,
          studentList: studentList.value,
          examineStatus: planStatus.value,
          teachPlanId: teachPlanId,
          comment: {
            passReason:
              planStatus.value === 1 && res.json ? res.json.comment : "",
            failReason:
              planStatus.value === 2 && res.json ? res.json.comment : "",
          },
        },
        { zIndex: "3000", hiddenBack: false }
      );
      queryPlanStatus();
    };
    /** 保存审核状态和意见 */
    const saveExamineStatus = async (status) => {
      if (planStatus.value !== 1 && teachPlanInfo.value) {
        status === 1 && passBtn.value.click();
        status === 2 && failBtn.value.click();
        return ElMessage.warning("教学计划审核未通过！");
      }
      let statusRes: any = await axios.post("/admin/lessonAudit/saveOrUpdate", {
        id: props.examineInfo.id,
        status,
      });
      let commentRes: any = await axios.post(
        "/admin/lessonAuditComment/saveOrUpdate",
        {
          auditId: props.examineInfo.id,
          comment: status === 1 ? passReason.value : failReason.value,
        }
      );
      let lessonRes: any = await axios.post("/admin/lessonInfo/saveOrUpdate", {
        id: props.examineInfo.lessonThirdId,
        status: status === 1 ? 3 : 2,
      });
      lessonRes.result &&
        commentRes.result &&
        statusRes &&
        ElMessage.success("审核成功");

      lessonRes.result && commentRes.result && statusRes && close(true);
    };
    const queryPlanStatus = () => {
      let params = {
        lessonId: props.examineInfo.type === 1 ? props.examineInfo.contractId : props.examineInfo.lessonId,
        version: props.examineInfo.bindVersion,
      }
      axios.post(`/admin/lessonTimesAudit/query`, params)
        .then((res: any) => {
          if (!res.result) return ElMessage.error(res.msg);
          planStatus.value = res.json.length > 0 ? res.json[0].status : 0;
        });
    };
    queryPlanStatus();
    const filterHandoutCount = () => {
      if (classType.value !== "handout") {
        return questionCount.value;
      }
      let flattenInfo = flattenMap(paperInfo.value.content);
      return flattenInfo.filter((e) => e.type === 4 || e.type === 8).length;
    };
    const filterknowledgeNames = () => {
      if (!paperInfo.value.content) return false;
      return paperInfo.value.content
        .filter((e) => {
          return e.type === 3;
        })
        .map((ele) => ele.content)
        .join(",");
    };
    /** 铺平数组 */
    const flattenMap = (list) => {
      var newArr: any = [];
      list.forEach((element: any) => {
        newArr.push(element);
        if (element.child) {
          newArr.push.apply(newArr, flattenMap(element.child));
        } else {
        }
      });
      return newArr;
    };
    const hiddenPassPop = () => {
      passBtn.value.click();
    };
    const hiddenFailPop = () => {
      failBtn.value.click();
    };
    watch(classType, () => {
      handoutId.value = "";
      if (urls[classType.value]) {
        queryDetail(urls[classType.value]);
      }
    });
    return {
      close,
      classLsit,
      classType,
      passReason,
      failReason,
      handoutId,
      queryDetail,
      detailData,
      filterTime,
      paperInfo,
      handoutTitle,
      flattenMap,
      filterHandoutCount,
      handoutSaveTime,
      filterknowledgeNames,
      passVisible,
      failVisible,
      testPaperPath,
      testPaper,
      questionCount,
      questionScore,
      studentList,
      teachPlanInfo,
      examineTeachPlan,
      homeworkSTime,
      homeworkETime,
      saveExamineStatus,
      planStatus,
      hiddenPassPop,
      hiddenFailPop,
      failBtn,
      passBtn,
      previewType,
      previewPath,
      basePath,
    };
  },
};
</script>

<style scoped lang="scss">
.examine-detail {
  background: #f4f5f9;
  .examine-header {
    width: 100%;
    height: 60px;
    background: #72b22a;
    box-shadow: 0px 0px 3px 0px rgba(45, 113, 183, 0.15);
    display: grid;
    grid-template: auto / 20% 60% 20%;
    > span {
      cursor: pointer;
      margin-left: 70px;
      margin-top: 18px;
      color: #fff;
      font-size: 16px;
    }
    > div {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      font-size: 16px;
    }
    .options {
      :nth-child(1) {
        margin-right: 10px;
      }
      > .options-btn {
        background: #ffffff;
        border-radius: 18px;
        font-size: 14px;
        color: #72b22a;
        padding: 7px 34px;
        cursor: pointer;
      }
    }
  }
  .examine-content {
    margin: 30px 160px 10px 160px;
    height: calc(100vh - 100px);
    background: #ffffff;
    box-shadow: 0px 1px 6px 0px rgba(91, 125, 255, 0.08);
    border-radius: 6px;
    border: 1px solid #ebf0fc;
    padding: 0 20px;
    .cus-tabs {
      flex: auto;
      text-align: left;
      border-bottom: 1px solid #dee4f1;
      padding-top: 15px;
      ul {
        display: inline-block;
      }
      li {
        float: left;
        padding: 10px 35px;
        color: #000;
        font-size: 16px;
        list-style: none;
        position: relative;
        cursor: pointer;
        &.active::after {
          content: "";
          display: block;
          width: 70%;
          height: 5px;
          background: #72b22a;
          border-radius: 3px;
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
        }
        &.active {
          color: #72b22a;
        }
      }
    }
    .deital-container {
      height: calc(100% - 86px);
      display: flex;
      padding-top: 20px;
      .preview-container {
        flex: 1;
        border: 1px solid #dee4f1;
        height: 100%;
        overflow: auto;
        display: flex;
        justify-content: center;
        align-items: center;
        :deep(.class-preview) {
          width: 100%;
        }
        :deep(.content) {
          height: 100% !important;
          width: 100%;
          .paper_container {
            padding: 0;
            width: 100%;
          }
        }
        :deep(.paper-update-container) {
          width: 100%;
          > .header {
            display: none !important;
          }
        }
      }
      .detail-info {
        width: 256px;
        margin-left: 20px;
        overflow-y: auto;
        > :nth-child(1) {
          margin-bottom: 30px;
        }
        .prepare-info {
          border-radius: 4px;
          border: 1px solid #72b22a;
          .prepare-title {
            background: #72b22a;
            border-radius: 4px 4px 0px 0px;
            padding: 10px 20px;
            font-size: 18px;
            color: #ffffff;
            position: relative;
            > img {
              height: 77px;
              width: 66px;
              position: absolute;
              top: 0;
              right: 12px;
            }
          }
          .other-title {
            font-size: 16px;
            text-align: center;
          }
          .prepare-content {
            padding: 15px 10px;
            .prepare-info-item {
              margin-bottom: 10px;
              :nth-child(1) {
                font-size: 14px;
                color: #333333;
              }
              .item-value {
                font-size: 14px;
                color: #666666;
                margin-left: 10px;
              }
            }
            .teach-plan {
              background: #f5f7fa;
              border-radius: 4px;
              padding: 6px 0 18px 8px;
              .teach-plan-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0;
                > div {
                  display: flex;
                  align-items: center;
                  > img {
                    height: 24px;
                    width: 24px;
                    vertical-align: center;
                    margin-right: 5px;
                  }
                  > span {
                    font-size: 14px;
                    color: #72b22a;
                    text-align: center;
                  }
                }
                > span {
                  font-size: 12px;
                  padding: 2px 8px;
                  cursor: pointer;
                  text-align: center;
                  border-radius: 100px 0px 0px 100px;
                }
                .plan-status-fail {
                  color: #fc514f;
                  background: #ffefeb;
                }
                .plan-status-pass {
                  background: #74c874;
                  color: #fff;
                }
                .plan-status-normal {
                  background: #fff4df;
                  color: #faad14;
                }
                .plan-status-none {
                  color: #999999;
                  background: #ffffff;
                }
              }
              .teach-plan-title {
                font-size: 16px;
                color: #333333;
                margin: 10px 0;
              }
              .teach-plan-info {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding-right: 10px;
                font-size: 12px;
                color: #999999;
                .plan-info-label {
                  font-size: 12px;
                  color: #666666;
                }
              }
            }
          }
          .important-pointer {
            margin: 0 -10px -15px -10px;
            // display: flex;
            // height: 32px;
            background: rgba(#faad14, 0.1);
            position: relative;
            overflow: hidden;
            & > div {
              flex: 1 1 57px;
              // padding: 0 20px 0 20px;
              font-size: 12px;
              color: #666666;
              line-height: 32px;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
            .difficult {
              display: flex;
              padding: 0;
            }
            & > .difficult::before {
              content: "重难点";
              display: block;
              width: 100%;
              height: 100%;
              padding-left: 10px;
              color: #9f6e0c;
              line-height: 32px;
              font-size: 14px;
              background: #fcdb9b;
              box-sizing: border-box;
            }
            // & > .difficult::after {
            //   content: "";
            //   display: inline-block;
            //   width: 0;
            //   height: 0;
            //   border: solid 22px transparent;
            //   border-left-color: #fcdb9b;
            //   transform: scaleX(0.7);
            //   position: absolute;
            //   bottom: 0;
            //   right: -15px;
            //   margin-bottom: -6px;
            // }
          }
        }
      }
    }
  }
}
.examine-reason {
  font-size: 14px;
  color: #333333;
}
.cus-editor {
  width: 250px;
  height: 130px;
  margin-top: 10px;
  :deep(.cus__editor) {
    background: #f5f7fa;
  }
}
.examine-pop-option {
  display: flex;
  justify-content: flex-end;
  margin-top: 28px;
  :nth-child(1) {
    margin-right: 10px;
  }
}
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  background: rgba(#faad14, 0.1);
  color: #666666;
}
</style>
